package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.x.erp.model.*;
import com.x.erp.rpc.CarRpcService;
import com.x.erp.rpc.CarTypeRpcService;
import com.x.erp.rpc.LyvinRpcService;
import com.x.erp.rpc.ModelRpcService;
import com.x.erp.util.Constant;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.framework.remote.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 车型Controller
 */
@RestController
public class ModelController extends BaseController {

	@Reference
	private ModelRpcService modelRpcService;// 车型服务

	@Reference
	private CarTypeRpcService carTypeRpcService;// 车辆类型服务

	@Reference
	private CarRpcService carRpcService;// 车辆服务

	@Reference
	private LyvinRpcService lyvinRpcService;// 力扬vin解析记录

	@Autowired
	private HttpClient httpClient;

	/**
	 * 查询车型列表
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getModelList", method = { RequestMethod.GET, RequestMethod.POST })
	public ResultModel getModelList(Model model) {
		if (model == null || model.getSeriesId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车系ID不能为空！");
		}
		List<Model> modelList = modelRpcService.selectModelList(model);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", modelList);
	}

	/**
	 * 查询车身类型列表
	 * @param carType
	 * @return
	 */
	@RequestMapping(value = "/getCarTypeList", method = { RequestMethod.GET, RequestMethod.POST })
	public ResultModel getCarTypeList(CarType carType) {
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", carTypeRpcService.selectCarTypeList(carType));
	}

	/**
	 * 查询车辆配置
	 * 
	 * @param carId
	 * @return
	 */
	@RequestMapping(value = "/getCarConfById", method = { RequestMethod.GET, RequestMethod.POST })
	public ResultModel getCarConfById(String carId) {
		List<Map<String, Object>> carConfs = null;
		if (StringUtils.isNotEmpty(carId)) {
			CarConfInfo carConfInfo = new CarConfInfo();
			carConfInfo.setCarId(carId);
			carConfs = carRpcService.selectCarConfInfo(carConfInfo);
		} else {
			CarConf carConf = new CarConf();
			carConfs = carRpcService.selectCarConf(carConf);
		}
//		for (Map<String, Object> carConf : carConfs) {
//			if ((int) carConf.get("confParentId") == 0) {
//				List<Map<String, Object>> childCarConfMap = new ArrayList<>();
//				for (Map<String, Object> childCarConf : carConfs) {
//					if (childCarConf.get("confParentId") == carConf.get("confId")) {
//						childCarConfMap.add(childCarConf);
//					}
//				}
//				carConf.put("childCarConf", childCarConfMap);
//			}
//		}
//		for (int i = carConfs.size() - 1; i >= 0; i--) {
//			if ((int) carConfs.get(i).get("confParentId") != 0) {
//				carConfs.remove(i);
//			}
//		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", getCarConfByModel(carConfs, null));
	}

	/**
	 * 根据modelConf查询车型配置
	 * @param modelConf
	 * @return
	 */
	@RequestMapping(value = "/getModelConfById", method = { RequestMethod.GET, RequestMethod.POST })
	public ResultModel getModelConfById(ModelConf modelConf) {
		if (modelConf == null || modelConf.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型ID不能为空");
		}
		List<ModelConf> modelConfs = modelRpcService.selectModelConfList(modelConf);
		if (modelConfs != null && modelConfs.size() > 0) {
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", modelConfs.get(0));
		}
		return new ResultModel(ResultCode.RESULT_FAIL, "车型不存在");
	}

	/**
	 * 根据车型ID查询车辆配置
	 * @param modelConf
	 * @return
	 */
	@RequestMapping(value = "/model/getCarConfByModelId", method = { RequestMethod.GET, RequestMethod.POST })
	public ResultModel getCarConfByModelId(ModelConf modelConf) {
		if (modelConf == null || modelConf.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型ID不能为空");
		}
		List<ModelConf> modelConfs = modelRpcService.selectModelConfList(modelConf);
		if (modelConfs != null && modelConfs.size() > 0) {
			modelConf = modelConfs.get(0);
			List<Map<String, Object>> carConfs = carRpcService.selectCarConf(new CarConf());
			return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", getCarConfByModel(carConfs, modelConf));
		}
		return new ResultModel(ResultCode.RESULT_FAIL, "车型不存在");
	}

	/**
	 * 根据Id查询车型信息
	 * @param modelId
	 * @return
	 */
	@RequestMapping(value = "/getModelInfoById", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getModelInfoById(Integer modelId) {
		if (modelId == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型ID不能为空！");
		}
		Model model = new Model();
		model.setModelId(modelId);
		List<Model> models = modelRpcService.selectModelList(model);
		if (models == null || models.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型ID不能为空！");
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", models);
	}

	/**
	 * 根据Vin查询车型和配置信息
	 * @param vin
	 * @return
	 */
	@RequestMapping(value = "/model/getModelInfoByVin", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getModelInfoById(String vin) {
		if (StringUtils.isEmpty(vin)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "vin不能为空！");
		}
		String vinStr = vin.toUpperCase();
		if(vin.length() != 17 && vinStr.contains("I") || vinStr.contains("O") || vinStr.contains("Q")) {
			return new ResultModel(ResultCode.RESULT_FAIL, "vin格式错误！");
		}
		int[] modelIds = getModelIdByVin(vin);
		List<Model> models = new ArrayList<>();
		Model model = new Model();
		for (int modelId : modelIds) {
			model.setModelId(modelId);
			models.addAll(modelRpcService.selectModelAndConfList(model));
		}
		List<Map<String, Object>> carConfs = carRpcService.selectCarConf(new CarConf());
		for(Model m : models) {
			m.setModelConf(getCarConfByModel(carConfs, m.getBaseModelConf()));
			m.setBaseModelConf(null);
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", models);
	}

	private final String modelConfJson = "[{\"confName\":\"基本参数\",\"childCarConf\":[{\"confKey\":\"modelManufacturer\",\"confName\":\"厂商\",\"confValue\":\"无\"},{\"confKey\":\"modelEngineModel\",\"confName\":\"发动机\",\"confValue\":\"无\"},{\"confKey\":\"modelGearboxModality\",\"confName\":\"变速箱\",\"confValue\":\"无\"},{\"confKey\":\"modelBodywork\",\"confName\":\"车身结构\",\"confValue\":\"无\"}]},{\"confName\":\"车身\",\"childCarConf\":[{\"confKey\":\"modelLength\",\"confName\":\"长度\",\"confValue\":\"无\"},{\"confKey\":\"modelWidth\",\"confName\":\"宽度\",\"confValue\":\"无\"},{\"confKey\":\"modelHeight\",\"confName\":\"高度\",\"confValue\":\"无\"},{\"confKey\":\"modelWheelbase\",\"confName\":\"轴间距\",\"confValue\":\"无\"},{\"confKey\":\"modelBodywork\",\"confName\":\"车身结构\",\"confValue\":\"无\"}]},{\"confName\":\"发动机\",\"childCarConf\":[{\"confKey\":\"modelEngineModel\",\"confName\":\"发动机型号\",\"confValue\":\"无\"},{\"confKey\":\"modelDisplacement\",\"confName\":\"排量（l）\",\"confValue\":\"无\"},{\"confKey\":\"modelInletModel\",\"confName\":\"进气形式\",\"confValue\":\"无\"},{\"confKey\":\"modelCylinderArray\",\"confName\":\"气缸排列形式\",\"confValue\":\"无\"},{\"confKey\":\"modelCylinderNum\",\"confName\":\"气缸数（个）\",\"confValue\":\"无\"},{\"confKey\":\"modelFuelRoz\",\"confName\":\"燃料形式\",\"confValue\":\"无\"},{\"confKey\":\"modelEnviron\",\"confName\":\"环保标准\",\"confValue\":\"无\"}]},{\"confName\":\"变速箱\",\"childCarConf\":[{\"confKey\":\"modelGearboxModality\",\"confName\":\"变速箱类型\",\"confValue\":\"无\"},{\"confKey\":\"modelGearNum\",\"confName\":\"档位个数\",\"confValue\":\"无\"}]}]";
	@RequestMapping(value = "/model/carModelContrast", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel carModelContrast(String carInfo){
		if(StringUtils.isEmpty(carInfo)){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆id不能为空！");
		}
		List<String> carInfoList = null;
		try {
			carInfoList = JSON.parseArray(carInfo, String.class);
			if(carInfoList == null || carInfoList.isEmpty()){
				return new ResultModel(ResultCode.RESULT_FAIL, "请求数据有错误！");
			}
		}catch (Exception e){
			return new ResultModel(ResultCode.RESULT_FAIL, "请求数据有错误！");
		}
		List<List<Map<String, Object>>> res = new ArrayList<>();
		for(String str : carInfoList) {
			String carId = str.split(",")[0];
			Integer modelId = Integer.valueOf(str.split(",")[1]);
			if(StringUtils.isEmpty(carId) || modelId == null){
				return new ResultModel(ResultCode.RESULT_FAIL, "请求数据有错误！");
			}
			List<Model> models = modelRpcService.selectModelList(new Model(modelId));
			List<Map<String, Object>> resList = JSON.parseObject(modelConfJson, List.class);
			if (!models.isEmpty()) {
				Map<String, Object> modelMap = JSON.parseObject(JSON.toJSONString(models.get(0)), Map.class);
				for (Map<String, Object> resMap : resList) {
					List<Map<String, Object>> childCarConfList = (List<Map<String, Object>>) resMap.get("childCarConf");
					for (Map<String, Object> childCarConfMap : childCarConfList) {
						for (String key : childCarConfMap.keySet()) {
							if (modelMap.get(childCarConfMap.get(key)) != null && StringUtils.isNotEmpty(modelMap.get(childCarConfMap.get(key)).toString())) {
								childCarConfMap.put("confValue", modelMap.get(childCarConfMap.get(key)));
							}
						}
					}
				}
			}
			CarConfInfo carConfInfo = new CarConfInfo();
			carConfInfo.setCarId(carId);
			List<Map<String, Object>> carConfs = carRpcService.selectCarConfInfo(carConfInfo);
			resList.addAll(getCarConfByModel(carConfs, null));
			res.add(resList);
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 组装车辆配置
	 * @param carConfs
	 * @param modelConf
	 * @return
	 */
	private List<Map<String, Object>> getCarConfByModel(List<Map<String, Object>> carConfs, ModelConf modelConf){
		List<Map<String, Object>> carConfList = new ArrayList<>(carConfs);
		JSONObject jsonObject = null;
		if(modelConf != null) {
			jsonObject = JSONObject.parseObject(JSONObject.toJSONString(modelConf));
		}
		for (Map<String, Object> carConf : carConfList) {
			if ((int) carConf.get("confParentId") == 0) {
				List<Map<String, Object>> childCarConfMap = new ArrayList<>();
				for (Map<String, Object> childCarConf : carConfList) {
					if (childCarConf.get("confParentId") == carConf.get("confId")) {
						childCarConf.put("confValue", "无");
						childCarConfMap.add(childCarConf);
						carConf.put("childCarConf", childCarConfMap);
						if(jsonObject != null) {
							Integer confValue = jsonObject.getInteger(childCarConf.get("confKey").toString());
							if (confValue != null && confValue == 1) {
								childCarConf.put("selectedState", true);
								childCarConf.put("confValue", "有");
							}
						}
					}
				}
			}
		}
		for (int i = carConfList.size() - 1; i >= 0; i--) {
			if ((int) carConfList.get(i).get("confParentId") != 0) {
				carConfList.remove(i);
			}
		}
		return carConfList;
	}

	private int[] getModelIdByVin(String vin) {
		String xmlInput = "<root><appkey>a57c6c5fb9da708c</appkey><appsecret>7cbb1154a6e6452cb23e798516b22eee</appsecret><method>level.vehicle.vin.get</method><requestformat>json</requestformat><vin>" + vin + "</vin></root>";// 传参是XML格式的字符串，xmlInput中的特殊字符需要转义，比如<>
		xmlInput = xmlInput.replace("<", "&lt;");
		xmlInput = xmlInput.replace(">", "&gt;");
		String param = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
				+ "<soap12:Body>"
				+ " <LevelData xmlns=\"http://www.dat881.com/\">"
				+  "<xmlInput>" + xmlInput + "</xmlInput>" + "</LevelData>" // 接口传入参数
				+ "  </soap12:Body>" + "</soap12:Envelope>";
		String res = null;
		try {
			res = httpClient.doPostXml("http://service.vin114.net/req", param);
			lyvinRpcService.insertLyvin(new Lyvin(vin, res, this.getDate(0)));
//			res = new HttpClient().doPostXml("http://service.vin114.net/req", param);
			res = parserXml(res);
		} catch (Exception e) {
			logger.error("力扬vin解析，vin:" + vin + "，返回结果：" + res, e);
			return new int[0];
		}
		if(StringUtils.isNotEmpty(res)) {
			JSONObject obj = JSON.parseObject(res);
			if(obj.getJSONObject("Info").getBoolean("Success")) {
				JSONArray array = obj.getJSONArray("Result");
				if(array != null && !array.isEmpty()) {
					int[] modelIds = new int[array.size()];
					for (int i = 0; i < array.size(); i++) {
						modelIds[i] = array.getJSONObject(i).getInteger("QiYuanId");
					}
					return modelIds;
				}
			}else{
				logger.info("力扬vin解析，vin:" + vin + "，返回结果：" + res);
			}
		}
		return new int[0];
	}

	public String parserXml(String strXML) {
		if(StringUtils.isEmpty(strXML)){
			return null;
		}
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			StringReader sr = new StringReader(strXML);
			InputSource is = new InputSource(sr);
			Document doc = builder.parse(is);
			Element rootElement = doc.getDocumentElement();
			return rootElement.getFirstChild().getFirstChild().getTextContent();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加ip白名单
	 * @param ip
	 * @return
	 */
	@RequestMapping(value = "/model/setIpWhiteList")
	public ResultModel setIpWhiteList(String ip){
		if(StringUtils.isEmpty(ip)){
			return new ResultModel(ResultCode.RESULT_FAIL, "ip不能为空！");
		}
		Constant.setIpWhiteList(Constant.IP_WHITE_LIST + ";" + ip);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "添加成功");
	}
}
